package com.hulden.rpc.server;

import com.hulden.rpc.common.bean.RpcRequest;
import com.hulden.rpc.common.bean.RpcResponse;
import com.hulden.rpc.common.codec.RpcDecoder;
import com.hulden.rpc.common.codec.RpcEncoder;
import com.hulden.rpc.common.util.StringUtil;
import com.hulden.rpc.registry.ServiceRegistry;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


import java.util.HashMap;
import java.util.Map;

/**
 * RPC 服务器（用于发布RPC服务）
 *
 * @author hugo
 * @since 1.0.0
 */
public class RpcServer implements ApplicationContextAware,InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(RpcServer.class);

    private String serviceAddress;
    private ServiceRegistry serviceRegistry;

    /**
     * 存放服务名与服务对象之间的映射关系
     */
    private Map<String,Object> handlerMap = new HashMap<>();

    public RpcServer(String serviceAddress) {
        this.serviceAddress = serviceAddress;
    }

    public RpcServer(String serviceAddress, ServiceRegistry serviceRegistry) {
        this.serviceAddress = serviceAddress;
        this.serviceRegistry = serviceRegistry;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //创建并初始化 Netty 服务端 Bootstarp对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    pipeline.addLast(new RpcDecoder(RpcRequest.class));// 解码 RPC 请求
                    pipeline.addLast(new RpcEncoder(RpcResponse.class));// 编码 RPC 响应
                    pipeline.addLast(new RpcServerHandler(handlerMap));// 处理 RPC 请求

                }
            });

            bootstrap.option(ChannelOption.SO_BACKLOG,1024);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE,true);

            //获取RPC服务器的IP地址和端口
            String[] addressArray = StringUtil.split(serviceAddress,":");
            String ip = addressArray[0];
            int port = Integer.parseInt(addressArray[1]);

            //启动RPC服务
            ChannelFuture future = bootstrap.bind(ip,port).sync();

            //注册RPC服务
            if(serviceRegistry != null){
                for(String interfaceName : handlerMap.keySet()){
                    serviceRegistry.register(interfaceName,serviceAddress);
                    log.debug("register service: {} => {}", interfaceName, serviceAddress);
                }
            }
            log.debug("server started on port {}", port);
            //关闭RPC服务器
            future.channel().closeFuture().sync();
        }
        catch (Exception e){
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String,Object> serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class);
        if(MapUtils.isNotEmpty(serviceBeanMap)){
            for(Object serviceBean : serviceBeanMap.values()){
                RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
                String serviceName = rpcService.value().getName();
                String serviceVersion = rpcService.version();
                if(StringUtil.isNotEmpty(serviceVersion)){
                    serviceName += "-" + serviceVersion;
                }
                handlerMap.put(serviceName,serviceBean);
            }
        }
    }
}
